{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "44bf287d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee38b171",
   "metadata": {},
   "outputs": [],
   "source": [
    "class SecureModel(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(SecureModel, self).__init__()\n",
    "        self.layer1 = nn.Linear(10, 20)\n",
    "        self.layer2 = nn.Linear(20, 2)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = torch.relu(self.layer1(x))\n",
    "        return torch.sigmoid(self.layer2(x))\n",
    "\n",
    "\n",
    "# 转换为TorchScript\n",
    "model = SecureModel()\n",
    "# model = SecureModel().to(\"cuda\")\n",
    "model = model.eval()\n",
    "scripted_model = torch.jit.script(model)  # 保留控制流\n",
    "\n",
    "# 模型优化\n",
    "scripted_model = torch.jit.freeze(scripted_model)\n",
    "scripted_model = torch.jit.optimize_for_inference(scripted_model)\n",
    "\n",
    "\n",
    "@torch.jit.script\n",
    "def annotated_fn(x: torch.Tensor, y: float) -> torch.Tensor:\n",
    "    return x * y\n",
    "\n",
    "\n",
    "# 保存模型\n",
    "pt_file = \"secure_model.pt\"\n",
    "scripted_model.save(pt_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6c99faf",
   "metadata": {},
   "outputs": [],
   "source": [
    "model: torch.nn.Module = torch.jit.load(pt_file)\n",
    "output = model(torch.rand(1, 10))\n",
    "print(output)\n",
    "\n",
    "# 打印模型图\n",
    "print(model.graph)\n",
    "\n",
    "# 打印模型代码\n",
    "print(model.code)\n",
    "\n",
    "# model.load_state_dict()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
